package top.oylan.manager.controller.api;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.BeanUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import top.oylan.manager.entity.User;
import top.oylan.manager.entity.api.LoginApi;
import top.oylan.manager.entity.api.entity.UserEntity;
import top.oylan.manager.entity.api.result.LoginResult;
import top.oylan.manager.service.UserService;
import top.oylan.manager.tools.ApiUtils;

import javax.annotation.Resource;
/**
 * @Author abduahad
 * @Description ${description}
 * @Date 2019-06-23
 */
@RestController
@RequestMapping("/api")
@Api(value = "auth", description = "授权接口", produces = MediaType.APPLICATION_JSON_VALUE)
public class ApiAuthController {

    @Resource
    UserService userService;

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ApiOperation(value = "登录",response = LoginApi.class,httpMethod = "GET")
    public LoginApi login(@RequestParam("phone") String phone,@RequestParam("password") String password){
        LoginApi api = new LoginApi();

        User  user = userService.findUserByPhone(phone);

        api.setCode((byte)0);
        if(user == null){
            api.setMsg("用户不存在");
        }else{
            ByteSource salt = ByteSource.Util.bytes(user.getId().toString());
            SimpleHash simpleHash = new SimpleHash("md5", password, salt, 12);
            if(user.getPassword().equals(simpleHash.toString())){
                LoginResult loginResult = new LoginResult();
                UserEntity userEntity = new UserEntity();
                BeanUtils.copyProperties(user,userEntity);
                loginResult.setUserEntity(userEntity);
                ApiUtils.addRightData(api,"登录成功",loginResult);
            }else{
                api.setMsg("密码错误");
            }
        }
        return api;
    }
}
